var net = require("net");
var os = require("os");
var Fiber = require("fibers");
var cookie = require("cookie");
var role = require("./role");
var origin = require("../origin");
var config_template = require("./config.template/config.template");
var config_base_template = require("./config.template/config.base.template");
var BusCon = require("../../core/bus/_con");
var GoodsCon = require("../../core/goods/_con");
var AchCon = require("../../core/ach/_con");
var network = os.networkInterfaces();
var host;
Object.keys(network).some(function(network_name) {
	return network[network_name].some(function(network_info) {
		if (network_info.internal && network.family === "IPv4") {
			host = network_info.address
			return true;
		}
	})
});
_str_to_js = function(str) {
	var wrap_str = JSON.stringify(str);
	return 'document.title = (' + wrap_str + ')'
};
//TCP协议端口
var port = 3001;
//连接池
var connPool = Object.create(null);
module.exports = {
	prefix: "/pre_build",
	_init: function(app) {
		var server = net.Server();

		function _start_server(e) {
			if (e) {
				console.error("辅助文件服务器搭建失败", e);
				port += 1;
				server.listen(port, _start_server);
			} else {
				console.log("辅助文件服务器搭建成功");
			}
		}
		server.listen(port, _start_server);
		server.on("connection", function(conn) {
			var bufferList = [];
			conn.on("data", function(data) {
				data = data.toString();
				if (!conn.client_id) { //未初始化，默认为初始化事件来处罚
					conn.emit("data-end", data)
				} else {
					bufferList.push(data);
					//发现结束符，开始解析
					if (data.indexOf(conn.client_id) !== -1) {
						conn.emit("data-parser")
					}
				}
			});
			conn.on("data-parser", function() {
				var data = bufferList.join("");
				var index = data.indexOf(conn.client_id);
				var left_data = data.substr(0, index);
				var right_data = data.substr(index + conn.client_id.length);
				conn.emit("data-end", left_data);

				bufferList = [];
				bufferList.push(right_data);
				if (right_data.indexOf(conn.client_id) !== -1) {
					conn.emit("data-parser")
				}
			});
			conn.on("data-end", function(data) {
				Fiber(function() {

					var _result = {};
					try {
						json_config = JSON.parse(data.toString());
						if (!conn.client_id && !json_config.client_id) {
							throwCusError("not find:client_id");
						}
						if (!json_config.type) {
							throwCusError("not find:type");
						}
					} catch (e) {
						_result.error = String(e);
					}
					if (!_result.error) {
						_result.response_id = json_config.response_id;
						switch (json_config.type) {
							case "init":
								_result.response_id = "server_socket-init";
								connPool[conn.client_id = json_config.client_id] = conn;
								break;
							case "get-dotnar_render_data":
								var host = json_config.host;
								var bus_id = origin.white_list_map[host];
								var cookie_str = json_config.cookie;
								var data_list = json_config.data_list || [];
								var _result_data = _result.data = {};
								//BUS默认统一提供appConfig和busInfo
								if (true && data_list.indexOf("appConfig") !== -1 && host) {
									_result_data.appConfig = config_template(host);
								}
								if (true && data_list.indexOf("busInfo") !== -1 && bus_id) {
									_result_data.busInfo = JSON.parse(JSON.stringifySecurity(BusCon.get(bus_id)));
								}
								//任意权限都可以获取appConfigBase
								if (data_list.indexOf("appConfigBase") !== -1 && host) {
									_result_data.appConfigBase = config_base_template(host);

								}
								//登录者信息不再提供，统一使用AJAX实现
								if (false && data_list.indexOf("loginUser") !== -1 && cookie_str) {
									var mode = {
										cookies: {
											data: cookie.parse(cookie_str),
											get: function(key) {
												return mode.cookies.data[key]
											},
											set: function(key, value) {
												return mode.cookies.data[key] = value;
											}
										}
									};
									try {
										var user = role.getUser(mode);
									} catch (e) {
										console.error(e)
									}
									_result_data.loginUser = user;
								}
								//可选，提供商品信息
								var goods_id = json_config.goods_id;
								if (data_list.indexOf("goodsInfo") !== -1 && goods_id) {
									_result.goodsInfo = GoodsCon.get(goods_id);
								}
								//可选，提供订单信息
								var ach_id = json_config.ach_id;
								if (data_list.indexOf("achInfo") !== -1 && ach_id) {
									_result.achInfo = AchCon.get(ach_id);
								}

								break;
						}
					}
					// console.log(_result);
					conn.send(JSON.stringify(_result));
				}).run();
			});
			conn.send = function(data) {
				if (!conn.client_id) {
					console.error("客户端未初始化，无法返回数据");
				} else {
					conn.write(data + conn.client_id);
				}
			};
			// conn.on("end", function() {
			// 	var data = Buffer.concat(bufferList);
			// 	bufferList = [];
			// });
			function _onerror() {
				bufferList = [];
				delete connPool[conn.client_id];
				console.log("与文件服务器连接断开");
			};
			conn.on("close", _onerror);
			conn.on("error", _onerror);
		});
	},
	get: {
		"/": function() {
			var query = this.request.query;
			var client_id = query.client_id;
			var visitor_id = query.visitor_id;
			this.body = _str_to_js(Math.random() + "|" + visitor_id);
		},
		"/base_config": function() {
			this.body = JSON.stringify({
				host: host,
				network: network,
				port: port,
			});
		}
	}
}